import java.util.Stack;

public class DecodeString {
    // leetcode 字符串编码
    // https://leetcode.cn/problems/decode-string/description/?envType=study-plan-v2&envId=top-100-liked
    public String decodeString(String s) {
        Stack<Integer> stack1 = new Stack<>();
        Stack<StringBuilder> stack2 = new Stack<>();
        stack2.add(new StringBuilder());
        StringBuilder ret = new StringBuilder();
        int index = 0, len = s.length();
        while (index < len) {
            char c = s.charAt(index);
            if (c >= '0' && c <= '9') {
                int tmp = 0;
                while (index < len && s.charAt(index) >= '0' && s.charAt(index) <= '9') {
                    tmp = tmp * 10 + (s.charAt(index++) - '0');
                }
                stack1.add(tmp);
            }else if (c == '['){
                index++;
                StringBuilder newSb = new StringBuilder();
                while (index < len && s.charAt(index) >= 'a' && s.charAt(index) <= 'z') {
                    newSb.append(s.charAt(index++));
                }
                stack2.add(newSb);
            }else if (c == ']') {
                int num = stack1.pop();
                StringBuilder str = stack2.pop();
                StringBuilder newSb = new StringBuilder();
                for (int i = 0; i < num; i++) {
                    newSb.append(str);
                }
                stack2.peek().append(newSb);
                index++;
            }else {
                StringBuilder newSb = new StringBuilder();
                while (index < len && s.charAt(index) >= 'a' && s.charAt(index) <= 'z') {
                    newSb.append(s.charAt(index++));
                }
                stack2.peek().append(newSb);
            }
        }
        return stack2.peek().toString();
    }

    public static void main(String[] args) {
        DecodeString decodeString = new DecodeString();
        System.out.println(decodeString.decodeString("3[a]2[bc]"));
    }
}
